package com.travel.api.service.oss.impl

import com.aliyun.oss.OSSClient
import com.travel.api.service.oss.OSSService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.util.StringUtils
import org.springframework.web.multipart.MultipartFile
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import java.net.URL

import javax.annotation.PostConstruct
import com.aliyun.oss.model.ObjectMetadata
import java.util.*


/**
 * @ClassName OSSServiceImpl
 * @Author liguangyao
 * @Date 28/8/18 下午5:48
 * @Version 1.0
 */
@Service
class OSSServiceImpl : OSSService {

    private val log = LoggerFactory.getLogger(OSSServiceImpl::class.java)

    @Value("\${oss.endpoint}")
    private val OSS_ENDPOINT: String? = null

    @Value("\${oss.access.key.id}")
    private val OSS_ACCESS_KEY_ID: String? = null

    @Value("\${oss.access.key.secret}")
    private val OSS_ACCESS_KEY_SECRET: String? = null

    @Value("\${oss.bucket.name}")
    private val OSS_BUCKET_NAME: String? = null

    @Value("\${oss.folder.name}")
    private val OSS_FOLDER_NAME: String? = null

    private var ossClient: OSSClient? = null

    @PostConstruct
    fun init() {
        ossClient = OSSClient(
           OSS_ENDPOINT,
           OSS_ACCESS_KEY_ID!!,
           OSS_ACCESS_KEY_SECRET!!
        )
    }

    override fun create(bucketName: String): Boolean {
        if (ossClient!!.doesBucketExist(bucketName)) {
            log.info("[存储空间创建]该${bucketName}空间已存在")
            return false
        } else ossClient!!.createBucket(bucketName)
        log.info("[存储空间创建]该${bucketName}空间已创建")
        return true
    }

    override fun createFolder(bucketName: String?, folderName: String): Boolean {
        var bucketName = bucketName
        if(StringUtils.isEmpty(bucketName)) bucketName = OSS_BUCKET_NAME
        if(!ossClient!!.doesObjectExist(bucketName, folderName)) {
            ossClient!!.putObject(bucketName, folderName, ByteArrayInputStream(byteArrayOf(0)))
            log.info("[文件夹创建]该${folderName}文件夹创建成功")
            return true
        }
        log.info("[文件夹创建]该${folderName}文件夹已存在")
        return false
    }

    override fun upload(bucketName :String?, objectName: String, content: String): Boolean {
        var bucketName = bucketName
        if(StringUtils.isEmpty(bucketName)) bucketName = OSS_BUCKET_NAME

        val doesObjectExist = ossClient!!.doesObjectExist(bucketName, objectName)
        if (doesObjectExist) log.info("[OSS对象存储]该${objectName}对象已存在")
        ossClient!!.putObject(OSS_BUCKET_NAME, objectName
                , ByteArrayInputStream(content!!.toByteArray()))
        log.info("[OSS对象存储]该${objectName}对象已存储")
        return true
    }

    override fun download(bucketName: String?, objectName: String): String? {
        var bucketName = bucketName
        if(StringUtils.isEmpty(bucketName)) bucketName = OSS_BUCKET_NAME
        // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
        val ossObject = ossClient!!.getObject(bucketName, objectName)
        // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
        val stream = ossObject.objectContent
        if(!StringUtils.isEmpty(stream)) {
            val reader = BufferedReader(InputStreamReader(stream))
            var content = ""
            while (true) {
                val line = reader.readLine()
                if(StringUtils.isEmpty(line)) break
                content += line
            }
            log.info("[OSS对象下载]该${bucketName}内容为:$content")
            reader.close()
            return content
        }
        return null
    }

    override fun delete(bucketName: String, objectName: String?): Boolean {
        if(!StringUtils.isEmpty(bucketName) && StringUtils.isEmpty(objectName)) {
            ossClient!!.deleteBucket(bucketName)
        }
        if(!StringUtils.isEmpty(bucketName) && !StringUtils.isEmpty(objectName)) {
            ossClient!!.deleteObject(bucketName, objectName)
        }
        return true
    }

    override fun list(bucketName: String): List<String> {
        val list = ArrayList<String>()
        val listObjects = ossClient!!.listObjects(bucketName)
        for(obj in listObjects.objectSummaries) {
            list.add(obj.key)
        }
        return list
    }

    override fun uploadFile(bucketName: String?,folder: String?,file: MultipartFile): URL? {
        var bucketName = bucketName
        if(StringUtils.isEmpty(bucketName)) bucketName = OSS_BUCKET_NAME

        var folder = folder
        if(StringUtils.isEmpty(folder)) folder = OSS_FOLDER_NAME

        var url: URL? = null


        try {
            //以输入流的形式上传文件
            val inputStream = file.inputStream
            val fileName = file.name
            val type = fileName.substring(fileName.lastIndexOf(".") + 1)
            val random = (Math.random() * 900).toInt() + 10000
            //文件名
            val fileNameNew = fileName.replace(fileName, System.currentTimeMillis().toString() + random.toString() + "." + type)
            //文件大小
            val fileSize = file.size
            //创建上传Object的Metadata
            val metadata = ObjectMetadata()
            //上传的文件的长度
            metadata.contentLength = inputStream.available().toLong()
            //指定该Object被下载时的网页的缓存行为
            metadata.cacheControl = "no-cache"
            //指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache")
            //指定该Object被下载时的内容编码格式
            metadata.contentEncoding = "utf-8"
            //文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
            //如果没有扩展名则填默认值application/octet-stream
            metadata.contentType = getContentType(fileNameNew)
            //指定该Object被下载时的名称(指示MIME用户代理如何显示附加的文件,打开或下载,及文件名称)
            metadata.contentDisposition = "filename/filesize=" + fileNameNew + "/" + fileSize + "Byte."
            //上传文件 (上传文件流的形式)
            val putResult = ossClient!!.putObject(bucketName, folder + fileNameNew, inputStream, metadata)
            //解析结果
            url = getUrl(bucketName!!, folder + fileNameNew)
        } catch (e: Exception) {
            e.printStackTrace()
            log.error("上传阿里云OSS服务器异常." + e.message, e)
        }
        return url
    }

    // TODO 返回URL有问题需要修改

    fun getUrl(bucketName: String, key: String): URL {
        // 设置URL过期时间为10年
        val expiration = Date(Date().time + 3600L * 1000 * 24 * 365 * 10)
        // 生成URL
        return ossClient!!.generatePresignedUrl(bucketName, key, expiration)
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     * @param fileName 文件名
     * @return 文件的contentType
     */
    fun getContentType(fileName: String): String {
        //文件的后缀名
        val fileExtension = fileName.substring(fileName.lastIndexOf("."))
        if (".bmp".equals(fileExtension, ignoreCase = true)) {
            return "image/bmp"
        }
        if (".gif".equals(fileExtension, ignoreCase = true)) {
            return "image/gif"
        }
        if (".jpeg".equals(fileExtension, ignoreCase = true)
                || ".jpg".equals(fileExtension, ignoreCase = true)
                || ".png".equals(fileExtension, ignoreCase = true)) {
            return "image/jpeg"
        }
        if (".html".equals(fileExtension, ignoreCase = true)) {
            return "text/html"
        }
        if (".txt".equals(fileExtension, ignoreCase = true)) {
            return "text/plain"
        }
        if (".vsd".equals(fileExtension, ignoreCase = true)) {
            return "application/vnd.visio"
        }
        if (".ppt".equals(fileExtension, ignoreCase = true) || "pptx".equals(fileExtension, ignoreCase = true)) {
            return "application/vnd.ms-powerpoint"
        }
        if (".doc".equals(fileExtension, ignoreCase = true) || "docx".equals(fileExtension, ignoreCase = true)) {
            return "application/msword"
        }
        return if (".xml".equals(fileExtension, ignoreCase = true)) {
            "text/xml"
        } else "image/jpeg"
        //默认返回类型
    }
}
